/*
 * @Description: 评论框
 * @Autor: HuiSir<273250950@qq.com>
 * @Date: 2024-06-19 15:51:52
 * @LastEditTime: 2024-06-19 18:49:23
 */
import { ref, computed, reactive, toRefs } from "../../utils/vue.esm.js";
import Smiley from '../smiley.js'
import { loading2 } from "../../utils/loading.js";
import { createComment } from "../api/comment.js";

const template = /*html*/ `
<!-- 评论表单 -->
<div class="comment-form">
  <ul class="user-info" :class="{show: textareaFocus}">
    <li class="author">
      <label>昵称 {{requireNameEmail ? '*' : ''}}</label>
      <input type="text" 
        name="author" 
        id="author" 
        v-model="commentUserInfo.commentAuthor" 
        tabindex="1" 
        required="true" 
        placeholder="请输入您的昵称"
      />
    </li>
    <li class="email">
      <label>邮箱 {{requireNameEmail ? '*' : ''}}</label>
      <input type="text" 
        name="email" 
        id="email" 
        v-model="commentUserInfo.commentAuthorEmail" 
        tabindex="2" 
        required="true" 
        placeholder="请输入邮箱地址"
      />
    </li>
    <li class="url">
      <label>网站</label>
      <input type="text" 
        name="url" 
        id="url" 
        v-model="commentUserInfo.commentAuthorUrl" 
        tabindex="3" 
        placeholder="请输入您的网址"
      />
    </li>
  </ul>
  <div class="content-box">
    <textarea name="comment" 
      id="comment"
      tabindex="4" 
      :placeholder="textareaPlaceholder" 
      @keydown="bindSubmit($event, 'enter')" 
      @focus="textareaFocus = true" />
  </div>
  <div class="buttons">
    <div class="smilies myemoji">
      <svg @click="showSmiley = !showSmiley" t="1716971459857" class="icon myemoji" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2281" width="29" height="29"><path class="myemoji" d="M519.703 736.172c-87.139 0-158.472-64.737-170.317-148.617h-43.263c12.114 107.775 102.492 191.861 213.498 191.861s201.393-84.086 213.507-191.861h-43.11c-11.835 83.88-83.178 148.617-170.317 148.617zM512 62c-248.526 0-450 201.465-450 450 0 248.517 201.474 450 450 450 248.526 0 450-201.483 450-450 0-248.535-201.474-450-450-450zM511.964 916.992c-223.677 0-405.008-181.323-405.008-404.992 0-223.677 181.323-405.008 405.008-405.008 223.668 0 405 181.323 405 405.008 0 223.668-181.332 404.992-405 404.992zM638.189 463.598c27.306 0 49.436-22.14 49.436-49.436 0-27.306-22.131-49.436-49.436-49.436-27.306 0-49.447 22.131-49.447 49.436 0 27.297 22.131 49.437 49.447 49.437zM380.807 463.598c27.306 0 49.436-22.14 49.436-49.436 0-27.306-22.14-49.436-49.436-49.436-27.315 0-49.447 22.131-49.447 49.436 0 27.297 22.131 49.437 49.447 49.437z" p-id="2282" fill="#c5c5c5"></path></svg>
      <Smiley v-if="showSmiley" @smileClick="showSmiley = false" />
    </div>
    <div class="submits">
      <button v-if="isReply" @click="$emit('cancelReply')">取消回复</button>
      <button @click="bindSubmit" :disabled="submitLoading">
        <template v-if="submitLoading">发布中${loading2}</template>
        <template v-else>发布评论</template>
      </button>
    </div>
  </div>
</div>
`;
export default {
  name: 'CommentForm',
  template,
  components: { Smiley },
  emits: ['createEnd', 'cancelReply'],
  props: ['requireNameEmail', 'haveComments', 'commentsNumber', 'isFocus', 'isReply', 'parentId'],
  setup(props, context) {
    const { requireNameEmail, haveComments, commentsNumber, isFocus, isReply, parentId } = toRefs(props);

    const postId = computed(() =>
      document.getElementById("Article").getAttribute("post-id")
    );

    const textareaFocus = ref(!!isFocus.value);

    const showSmiley = ref(false);

    const submitLoading = ref(false);

    // 评论框占位
    const textareaPlaceholder = computed(() => {
      return haveComments.value
        ? `已经有${commentsNumber.value}人抢在你前面了，要说点什么？`
        : "还没有人抢沙发呢，赶紧抢一下~";
    });

    // 评论用户信息
    const getUserInfoTemp = localStorage.getItem("commentUserInfo");
    const commentUserInfo = reactive(
      getUserInfoTemp
        ? JSON.parse(getUserInfoTemp)
        : {
          commentAuthor: "",
          commentAuthorEmail: "",
          commentAuthorUrl: "",
        }
    );

    const doCreate = () => {
      if (submitLoading.value) {
        return;
      }
      submitLoading.value = true;
      const { commentAuthor, commentAuthorEmail, commentAuthorUrl } = commentUserInfo;

      // 验证
      if (requireNameEmail.value) {
        if (!commentAuthor.trim()) {
          submitLoading.value = false;
          alert('请输入昵称');
          return;
        }
        if (!commentAuthorEmail.trim()) {
          submitLoading.value = false;
          alert('请输入邮箱');
          return;
        }
        if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(commentAuthorEmail)) {
          submitLoading.value = false;
          alert('请输入正确的邮箱地址');
          return;
        }
      }

      const $comment = document.getElementById('comment');

      // 验证
      if (!$comment.value.trim()) {
        submitLoading.value = false;
        alert('请输入评论');
        return;
      }

      createComment({
        // id: '1539',
        authorEmail: commentAuthorEmail,
        authorName: commentAuthor,
        authorUrl: commentAuthorUrl,
        content: $comment.value,
        parentId: parentId.value, 
        postId: postId.value,
      }).then((res) => {
        if (res.error) {
          alert(res.error)
        } else {
          res.comment.child_list = [];
          context.emit('createEnd', res.comment);
        }
        $comment.value = '';
        submitLoading.value = false;
      }).catch(() => {
        submitLoading.value = false;
      });;
    };

    const bindSubmit = (event, flag) => {
      if(flag==='enter' && (!event.ctrlKey||event.keyCode!=13)){
        return;
      }
      // 存缓存
      localStorage.setItem("commentUserInfo", JSON.stringify(commentUserInfo));
      doCreate();
      return false;
    };

    // 点击空白关闭表情
    window.addEventListener("click", (e)=>{
      if(!e.target.classList.contains('myemoji') && showSmiley.value){
        showSmiley.value = false;
      }
    })

    return {
      textareaFocus,
      textareaPlaceholder,
      commentUserInfo,
      showSmiley,
      submitLoading,
      bindSubmit,
      requireNameEmail,
      isReply,
    };
  },
};
